当我尝试cout
get 函数时,它没有返回任何值!
我的头文件:
#pragma once
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Dog
{
private:
string dogName = "Max";
public:
Dog();
void talking();
void jumping();
void setDogName(string newDogName);
///////thats the function /////
string getDogName();
};
我的cpp文件:
#include "stdafx.h"
#include <iostream>
#include <string>
#include "Dog.h"
using namespace std;
Dog::Dog() {
cout << " Dog has been Created " << endl;
}
void Dog::setDogName(string newDogName)
{
newDogName = dogName;
}
string Dog::getDogName()
{
return dogName;
}
和我的 main.cpp 文件:
#include "stdafx.h"
#include <iostream>
#include "Dog.h"
#include "Cat.h"
int main()
{
Dog ewila;
ewila.setDogName("3wila");
cout << ewila.getDogName();
return 0;
}
我正在学习新的 C++,所以我不知道发生了什么,即使我尝试自己键入 ewila.getDogName();
但它什么也没做
我试图将 setDogname()
存储在一个变量中以返回 getDogName()
并且我也不知道我做错了什么
还有: 我使用 visual studio 2017 并且我从 visual c++ 2015 MSBuild 命令提示符运行程序
最佳答案
问题出在函数 void Dog::setDogName(string newDogName)
的 newDogName = dogName;
行。您错误地使用了赋值运算符
(=
)。这应该是 dogName =newDogName;
因此更正后的 CPP 文件将是:
#include "stdafx.h"
#include <iostream>
#include <string>
#include "Dog.h"
using namespace std;
Dog::Dog() {
cout << " Dog has been Created " << endl;
}
void Dog::setDogName(string newDogName)
{
dogName = newDogName;
}
string Dog::getDogName()
{
return dogName;
}
关于c++ getter不返回值(NULL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49001379/