首先,我想通知您,我已经确切地搜索了有关我的以下问题的答案,但我是C ++的完全新手。
我来自C#和Java的奢华生活,现在试图学习一两个关于c ++的东西
这个问题是关于实例化的。
我使用code :: block作为我的首选IDE。
目前,我只是在尝试用C#(我实际上非常熟悉并且已经编写了几个应用程序)中所谓的内容进行玩耍
2个类
包含主要人员的类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Models.Person;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Person person = new Person();
Console.WriteLine(person.getName());
}
}
}
以及Person类:
namespace ConsoleApplication1
{
public class Person{
private string name = "Bob";
public string getName(){
return name;
}
}
}
(不用在意语法的好坏,这只是为了模拟我想要实现的内容)
我希望在C++中实现相同的功能。
我查阅了一些资料,学习了头文件的一些知识,并且掌握了一些语法。这是我目前拥有的代码。
main.cpp
#include <iostream>
using namespace std;
int main()
{
Person person;
cout << person->getName() << endl;
}
Person.h
#ifndef PERSON_H
#define PERSON_H
#include <string>
class Person
{
public:
Person();
virtual ~Person();
std::string getName();
protected:
private:
};
#endif // PERSON_H
player.cpp
#include "Person.h"
#include <string>
using std::string;
Person::Person()
{
//ctor
}
Person::~Person()
{
}
string Person::getName()
{
return name;
}
考虑上述代码,我有多个问题。
我从来没有找到一个好的来源告诉我是否应该使用
Person person;
实例化还是Person person = new Person();
?这两个中哪一个是我应该使用的?
另一个我渴望知道的问题是,我是在头文件还是类文件中定义类成员?
目前我收到以下错误:
“person”未在范围内声明,并且在“person”之前需要“;”。
我并不是要求您解决我的错误,在回答我的问题后,我会自己解决。