我现在正在学习 C++,并且一直在尝试类,只是为了弄清楚它们是如何工作的。我以前只用 Java 编写过类。
在我的代码中,我有一个类定义和一个要测试的驱动程序。在评论中,我提到了哪些有效,哪些无效。我真的很想知道为什么以一种方式实例化对象但以其他方式实例化对象会出错。是编译器、make 文件还是类代码?构造函数/默认构造函数?当我像教科书一样将我的代码与其他代码进行比较时,我看不出我哪里出错了。
在 Linux Mint 13 上使用:code::blocks 10.5。
头文件:
#ifndef ENEMY_H
#define ENEMY_H
#include <string>
using namespace std;
class Enemy
{
public:
Enemy();
Enemy(int, int, string);
~Enemy();
string display();
// setter and getters:
int getHP();
void setHP(int);
int getX();
void setX(int);
int getY();
void setY(int);
string getName();
void setName(string);
private:
int hitpoints;
int x_pos;
int y_pos;
string name;
};
#endif // ENEMY_H
成员函数定义:
#include "Enemy.h"
#include <iostream>
#include <string>
// default ctor
Enemy::Enemy()
{
cout << "Creating enemy with default ctor.\n";
}
//ctor
Enemy::Enemy(int x, int y, string str)
{
cout << "Creating object with name: " << str << endl;
setX(x);
setY(y);
setHP(100);
setName(str);
}
//dtor
Enemy::~Enemy()
{
cout << "destroying Enemy: " << name << endl;
}
string Enemy::display()
{
cout<<name<<" - x: "<<x_pos<<", y: "<<y_pos<<", HP: "<<hitpoints<<endl;
}
int Enemy::getHP(){
return hitpoints;
}
void Enemy::setHP(int hp){
hitpoints = hp;
}
int Enemy::getX(){
return x_pos;
}
void Enemy::setX(int x){
x_pos = x;
}
int Enemy::getY(){
return y_pos;
}
void Enemy::setY(int y){
y_pos = y;
}
string Enemy::getName(){
return name;
}
void Enemy::setName(string objectName){
name = objectName;
}
// end of function definitions
司机:
#include "Enemy.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Program started.\n" << endl;
// initialise a few Enemy objects
Enemy E1(1, 1, "E1");
Enemy E2(2, -4, "E2");
Enemy E3;
Enemy E4;
Enemy *E5 = new Enemy(4, 5, "E5");
E1.display(); // <- success!
E2.display(); // <- success!
E3.display(); // <- segmentation fault at run time
E4.display(); // <- segmentation fault at run time
E5.display(); // <- compile time error "request for member
// 'display'" in 'E5'. which is of
// non-class type 'enemy'
cout << "end of program.\n";
return 0;
}