c ++ getter没有返回值(NULL)

时间:2018-02-27 04:53:49

标签: c++ return console-application return-value getter

当我尝试cout获取功能时,它不会返回任何值!

我的头文件:

#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 ++ new所以我不知道发生了什么,即使我试图单独输入ewila.getDogName();它也没有做任何事情 我试图将setDogname()存储在变量中以返回getDogName()而且我也不知道我做错了什么 即时通讯使用 Visual Studio 2017 ,我从 visual c ++ 2015 MSBuild命令提示符运行该程序

1 个答案:

答案 0 :(得分:2)

问题出在函数newDogName = dogName;的第void Dog::setDogName(string newDogName)行。您错误地使用了assignment operator=)。这应该是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;
}