c++ getter不返回值(NULL)

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

当我尝试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/

相关文章:

始终返回相同 bool 值的 Python 函数

c# - 使用条件运算符时控制台将 char 显示为 int ( ? : )

c# - 如何在 C# 中以编程方式关闭 Windows XP Print Spooler 服务

c++ - 动态分配内存时程序有时会崩溃

c++ - 通过智能指针调用另一个类的成员函数

Python 在没有预期的情况下返回数据

.net - 从 .net 控制台应用程序调用 http url?

c++ - 哈希表是否允许重复值?

c++ - 在 Code::Blocks 中运行程序的附加命令行参数?

list - 从 clojure 中的函数返回列表