首页 > 解决方案 > 不能创建一个类的多个实例?

问题描述

我的问题是我想为不同的升级创建升级类的多个实例。也许是因为我习惯了 java,但我不能只输入Source first("first"), second("second");,因为如果我这样做并调用first.getName()例如,我会得到"second". 我制作了一个示例文件,我只写了我正在努力解决的问题,所以你不必试图理解我的代码混乱。

Source.cpp:我想要这个类的多个实例。

#include "Source.h"

std::string name;

Source::Source()
{

}

Source::Source(std::string nameToSet) 
{
    name = nameToSet;
}

std::string Source::getName()
{
    return name;

源.h

#pragma once
#include <string>
class Source {
public:
    Source();
    Source(std::string namel);
    std::string getName();
};

测试.cpp

#include "Source.h"
#include "iostream"

Source first("first"), second("second");

int main()
{
    std::cout << first.getName() << std::endl;
}

输出:第二

测试.h

#pragma once
#include <string>

标签: c++

解决方案


问题在于这一行:

std::string name;

这声明了一个名为name. 此变量不与任何Source实例关联。相反,您需要在Source类中声明一个字段:

class Source {
public:
    Source();
    Source(std::string namel);
    std::string getName();

// Add these two lines
private:
    std::string name;
};

这将为name每个Source. 我建议您研究一下类字段以及它们之间的差异publicprivate访问权限。


推荐阅读