按照C++primer plus第六版中第十四章14.7,14.8,14.9程序清单代码在vs2019中运行,出现编译错误,无法将常量字符指针初始化给字符指针。
// worker0.h -- working classes
#ifndef worker0_h_
#define worker0_h_
#include <string>
class Worker // an abstract base class
{
private:
std::string fullname;
long id;
public:
Worker() :fullname("noname"), id(0l) {}
Worker(const std::string& s, long n) :fullname(s), id(n) {}
virtual ~Worker() = 0; // pure virtual destructor
virtual void Set();
virtual void Show() const;
};
class Waiter :public Worker
{
private:
int panache;
public:
Waiter() :Worker(), panache(0) {}
Waiter(const std::string& s, long n, int p = 0) :Worker(s, n), panache(p) {}
Waiter(const Worker& wk, int p = 0) :Worker(wk), panache(0) {}
void Set();
void Show() const;
};
class Singer :public Worker
{
protected:
enum { other, alto, contralto, soprano, bass, baritone, tenor };
enum { Vtypes = 7 };
private:
static char* pv[Vtypes]; // string equivs of voice types // 声明字符指针数组
int voice;
public:
Singer():Worker(),voice(other) {}
Singer(const std::string& s, long n, int V = other) :Worker(s, n), voice(n) {}
Singer(const Worker& wk,int v = other):Worker(wk),voice(v) {}
void Set();
void Show() const;
};
#endif // !worker0_h_
头文件如上,方法定义如下
// worker0.cpp -- working class methods
#include <iostream>
#include "worker0.h"
using std::cout;
using std::cin;
using std::endl;
// Worker methods
void Worker::Set()
{
cout << "Enter worker's name: ";
getline(cin, fullname);
cout << "Enter worker's ID: ";
cin >> id;
while (cin.get() != '\n')
continue;
}
void Worker::Show() const
{
cout << "Name: " << fullname << endl;
cout << "Employee ID: " << id << endl;
}
// Waiter methods
void Waiter::Set()
{
Worker::Set();
cin >> panache;
while (cin.get() != '\n')
continue;
}
void Waiter::Show() const
{
Worker::Show();
cout << "Panache rating: " << panache << endl;
}
// Singer methods
char* Singer::pv[] = { "other","alto","contralto","soprano","bass","baritone","tenor" };
// 编译提示这里出现错误E0144
void Singer::Set()
{
Worker::Set();
cout << "Enter number for singer's vocal range:\n";
int i;
for (i = 0; i < Vtypes; i++)
{
cout << i << ": " << pv[i] << " ";
if (i % 4 == 3)
cout << endl;
}
if (i % 4 != 0)
cout << endl;
while (cin >> voice && (voice < 0 || voice >= Vtypes))
cout << "Please enter a value >= 0 and <" << Vtypes << endl;
while (cin.get() != '\n')
continue;
}
void Singer::Show() const
{
cout << "Category: singer\n";
Worker::Show();
cout << "Vocal range: " << pv[voice] << endl;
}
我完全对照代码复制过来的,想说该怎么修改使得编译通过。看到有方法是将项目的符合模式(conformance mode)修改为否(默认为是)。但是修改过后没有E0144错误,提示Singer类析构函数出错