您的位置:首页 > 编程语言 > C语言/C++

c++实例化对象

2014-10-15 15:34 155 查看
今天看到c++实例化对象,有点懵了。Activity_Log the_log (theLogPtr, Tree->GetBranch());这是那一段小代码,开始没看懂。java看习惯了总喜欢new一个对象。c++直接类名 + 对象名(如果有构造函数定义就变为 类名 + 对象名())。c++动态分配内存的时候才需要new一个对象,哎~我还是那么水

header1.h

#include <iostream>
#include <string.h>
using namespace std;//这里加上namespace是为使用string时,不用std::string

#ifndef __HEADER1__H
#define __HEADER1__H

class fruit{
private:
double price;
string name;
public:
fruit(double price, string name);
void show();
};

#endif


header1.cpp

#include <iostream>
#include <string>
#include "header1.h"

using namespace std;

fruit::fruit(double price, string name){
this->name = name;
this->price = price;
}
void fruit::show(){
cout<<"the fruit's name is:"<<this->name<<" ,the price is:"<<this->price<<endl;
}


test.cpp

#include <iostream>
#include "header1.h"

using namespace std;

int main(){
fruit apple(5.6, "apple");//这里实例化一个对象不需要new,直接类名+对象名就好了
apple.show();

return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: