在c ++中创建动态对象?

时间:2015-04-09 15:44:24

标签: c++

如果我的类名是TEST,我想创建一个TEST类的对象,其名称在运行时由用户给出? 我试过这个 -

#include<iostream>
#include<string.h>
#include<conio.h>
using namespace std;
class TEST
{
   void end()
   {
      cout<<"Hi";
   }
};
   int main()
{
  string name;
  cout<<"Give a object name";
  cin>>name;//taking name from user
  TEST name;//here i am getting error while creating object of TEST class 
  return 0;
}

1 个答案:

答案 0 :(得分:-1)

目前尚不清楚你在这里想要做什么,除了学习基本的c ++结构。这里有一些代码可以帮助你。

#include <iostream>
#include <string>
#include <map>

using namespace std;

class TEST
{
public:
    //Constructor - sets member string to input
    TEST( string input ) : _name( input )
    {
    }

    //Destructor called when object goes out of scope
    ~TEST()
    {
       cout << "Hi from destructor" << endl;
    }

    //Variable stored by the class
    string _name;
};

int main()
{
    string inputString;

    cout << "Give a object name";
    cin >> inputString;

    // Give name to your class instance through the constructor
    TEST foo( inputString );

    // Store a copy of the object "foo" in a map that can be referenced by name
    map< string, TEST > userNamedObjects;
    userNamedObjects.insert( { inputString, foo } );

    // Access the object's data based on user input name
    cout << "From map: " << userNamedObjects.at( inputString )._name << endl;

    // Sanity check
    cout << foo._name << endl;

    // Or set it directly
    foo._name = "Patrick Swayze";

    cout << foo._name << endl;

    // The stored object doesn't change, because it's a copy
    cout << "From map: " << userNamedObjects.at( inputString )._name << endl;
    return 0;
}