当前位置:  开发笔记 > 编程语言 > 正文

Cannot create multiple instances of a class?

如何解决《Cannotcreatemultipleinstancesofaclass?》经验,为你挑选了1个好方法。

My problem is that i want to create multiple instances of my upgrade class, for different upgrades. Maybe it's because i'm used to java but i can't just type Source first("first"), second("second"); because if i do and call first.getName() for example, i get "second". I made an example file where i only wrote what i'm struggling with, so you don't have to try to understand my mess of a code.

Source.cpp: I want multiple instances of this class.

#include "Source.h"

std::string name;

Source::Source()
{

}

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

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

Source.h

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

Test.cpp

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

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

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

Output: second

Test.h

#pragma once
#include 

Code-Apprent.. 9

The problem is with this line:

std::string name;

This declares a single global string named name. This variable is not associated with any Source instance. Instead, you need to declare a field inside the Source class:

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

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

This will give a name for each Source. I suggest you study about class fields and the differences between public and private access.



1> Code-Apprent..:

The problem is with this line:

std::string name;

This declares a single global string named name. This variable is not associated with any Source instance. Instead, you need to declare a field inside the Source class:

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

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

This will give a name for each Source. I suggest you study about class fields and the differences between public and private access.

推荐阅读
jerry613
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有