[英]Need help printing out a string
Im currently learning about classes in C++. 我目前正在学习C ++中的类。 Im coming from a java language background.
我来自Java语言背景。
I have a class called animals. 我有一堂课叫做动物。 the animals constructor has a parameter in which a string is required.
动物的构造函数有一个参数,其中需要一个字符串。 When i create an object of that class and try to print out the string that was passed to the constructor, it doesn't print out anything apart from a new line..
当我创建该类的对象并尝试打印出传递给构造函数的字符串时,除了换行之外,它不会打印任何内容。
ANIMAL CLASS 动物课
#include "animal.h"
#include <string>
#include <iostream>
using namespace std;
animal::animal(string nameofanimal)
{
string name = nameofanimal;
}
void animal::getName(){
cout << name << endl;
}
ANIMAL HEADER: 动物头:
#pragma once
#ifndef ANIMAL_H
#define ANIMAL_H
#include <string>
#include <iostream>
using namespace std;
class animal
{
private:
string name;
public:
animal(string x);
void getName();
};
#endif ANIMAL_H
MAIN CLASS 主班
#include "animal.h"
#include <string>
#include <iostream>
using namespace std;
int main()
{
animal firstAnimal("Bob");
firstAnimal.getName();
}
the output is nothing. 输出什么都没有。 this is a very basic code and honestly cant believe I don't know how to do such a simple task.
这是一个非常基本的代码,老实说我不能相信我不知道如何做这样一个简单的任务。 What I have noticed is that whenever I highlight the name varible in the animals constructor, the varible name in the getName() function doesn't highlight so im guessing this has something to do with pointers... I may be wrong though...
我注意到的是,每当我在动物构造函数中突出显示名称varible时,getName()函数中的变量名称就不会突出显示,因此我猜想这与指针有关……我可能是错的。 。
Change your animal
constructor definition as follows 如下更改
animal
构造函数定义
animal::animal(string nameofanimal) : name(nameofanimal) {
}
In your original definiton you have a local variable name
that shadows the class member variable: 在原始定义中,您有一个局部变量
name
,该name
遮盖了类成员变量:
animal::animal(string nameofanimal)
{
string name = nameofanimal; // <<< This sets only the local variable
}
The problem is you are storing value in local variable 问题是您将值存储在局部变量中
string name = nameofanimal;
while the value is not stored in actual data member of the class. 而该值未存储在该类的实际数据成员中。 To store it in data member use the following:
要将其存储在数据成员中,请使用以下命令:
name = nameofanimal;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.