【问题标题】:c++ getter not returning value (NULL)c ++ getter不返回值(NULL)
【发布时间】:2018-02-27 04:53:48
【问题描述】:

当我尝试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 命令提示符运行程序

【问题讨论】:

  • 在您的 setDogName 方法中执行以下操作:dogName = newDogName;
  • 如果您通过const string&amp; 传递字符串,您会在setDogName 函数中看到错误,因为编译器不允许分配给newDogName。换句话说void Dog::setDogName(const string&amp; newDogName).
  • 天哪!太感谢了 !!!!我什么都试过了,但不是那样!我太菜鸟了!!谢谢

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


【解决方案1】:

问题在于函数void Dog::setDogName(string newDogName) 的行newDogName = dogName;。您错误地使用了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;
}

【讨论】:

    猜你喜欢
    • 2021-05-04
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 2020-01-26
    • 1970-01-01
    • 2017-09-17
    相关资源
    最近更新 更多