已经在构造函数的char*前加const了,加了之后p2中的“school”不报错,但是p1中的“home”报错
Part1(point.h)
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
class point
{
private:
double x;
double y;
char *name;
public:
point(const char *n=NULL, double a=0.0 ,double b=0.0);
~point();
void dis();
};
Part2(class的源码)
#include<bits/stdc++.h>
#include<string.h>
#include"point.h"
using namespace std;
point::point(const char* n, double a, double b)
{
x = a;
y = b;
if (n)
{
name = new char[strlen(n)+1];
strcpy(name, n);
}
else
{
name = new char[8];
strcpy(name, "no name");
}
cout << name << "constructing" << endl;
}
point::~point()
{
cout << name << "distructing" << endl;
delete [] name;
}
void point::dis()
{
cout << name << ":" << x << "," << y << endl;
}
Part 3(主程序)
#include <iostream>
#include<bits/stdc++.h>
#include "point.h"
using namespace std;
int main()
{
point p1("home", 1.0, 2,0);
point p2("school", 3.0);
point p3;
p1.dis();
p2.dis();
p3.dis();
return 0;
}