#include<iostream> using std::cout; using std::cin; using std::endl; class cTextBlock { public: cTextBlock(const char *Text) { strcpy(pText, Text); } const char& operator[] (std::size_t position) { return pText[position]; } char *pText; }; int main() { cTextBlock cctb("Bingo Tesla"); cout << cctb.pText; cout << cctb[7]; return 0; } 哪里错了
时间: 2024-03-25 07:38:19 浏览: 35
在 `const char& operator[] (std::size_t position)` 函数中,返回的是一个对字符的引用,但是该函数并没有声明为 const,因此无法在 const 对象上调用该函数。应该将函数声明为 const,如下所示:
```
const char& operator[] (std::size_t position) const
{
return pText[position];
}
```
另外,在定义 `cTextBlock` 对象时,应该使用 const char* 类型的指针,而不是直接传入字符串常量,如下所示:
```
const char* str = "Bingo Tesla";
cTextBlock cctb(str);
```
相关问题
下面这段代码的错误是什么#include <iostream> #include <vector> namespace my_std { using std::cin; using std::cout; using std::endl; using std::swap; using std::vector; } using namespace my_std; class MySort { public: /选择排序/ template<typename T> void SelectionSort(vector<T> &arr); }; template<typename T> void (SelectionPtr) (vector<T>&) = &MySort::SelectionSort; //指针函数
这段代码存在一个语法错误。具体来说,`SelectionPtr` 的定义中,函数指针类型 `void (vector<T>&)` 之前需要加上 `(*)`,表示这是一个指针类型。同时,由于 `SelectionSort` 是一个模板函数,需要在定义时指定其模板参数类型,否则编译器无法确定其模板参数类型。因此,可以将 `SelectionPtr` 的类型定义修改为:
```
template<typename T>
using SelectionPtr = void (MySort::*)(vector<T>&);
SelectionPtr<int> ptr = &MySort::SelectionSort<int>; // 指向 MySort::SelectionSort<vector<int>> 的指针
```
这样,`SelectionPtr` 就成为了一个指向 `MySort::SelectionSort` 函数的指针类型,其模板参数类型为 `int`,该函数接受一个 `vector<int>&` 类型的引用作为参数,返回值为 `void`。然后,将 `SelectionPtr` 指向 `MySort::SelectionSort<vector<int>>` 的实例化版本即可。
注意,由于 `SelectionSort` 是一个模板函数,因此在定义 `SelectionPtr` 时需要同时指定其模板参数类型,否则编译器无法确定其类型。
#include <iostream> #include <string> using namespace std; class Student {public: void get_value() {cin>>num>>name>>sex;} void display( ) {cout<<"num: "<<num<<endl; cout<<"name: "<<name<<endl; cout<<"sex: "<<sex<<endl;} private : int num; string name; char sex; }; /*在这里添加派生类的定义*/ int main() {Student1 stud1; stud1.get_value(); stud1.get_value_1(); stud1.display(); stud1.display_1(); return 0; }
这段代码定义了一个基类 `Student` 和一个派生类 `Student1`,其中 `Student1` 继承自 `Student`。
派生类 `Student1` 增加了两个成员函数 `get_value_1()` 和 `display_1()`,用于获取和显示学生的成绩信息。
完整的代码如下:
```
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
void get_value() {cin>>num>>name>>sex;}
void display() {cout<<"num: "<<num<<endl; cout<<"name: "<<name<<endl; cout<<"sex: "<<sex<<endl;}
private:
int num;
string name;
char sex;
};
class Student1 : public Student
{
public:
void get_value_1() {cin>>English>>math>>physics;}
void display_1() {cout<<"English: "<<English<<endl; cout<<"math: "<<math<<endl; cout<<"physics: "<<physics<<endl;}
private:
int English;
int math;
int physics;
};
int main()
{
Student1 stud1;
stud1.get_value();
stud1.get_value_1();
stud1.display();
stud1.display_1();
return 0;
}
```
注意,在派生类中,需要使用 `public` 继承方式,否则派生类无法访问基类的公有成员。同时,派生类中增加的成员函数和成员变量可以在派生类对象中调用和使用。