1/1自定义了两个类:一个是button,一个是window
标准库中使用了string,vector
button和string
button和window
string和window
vector和window
1/2 button.close函数不适合添加inline,因为这个函数的功能是在引用表示窗口结束,只会调用一次,window.close同理;至于添加const,由于在窗口类的自定义时设计只在vector的第一个元素中使用,而第一个元素是button("close")是一个用close定义的无名类,因此const没有意义。
window.add-button本身就是要改变里面的buttons,因此不能添加const,不需要多次调用,因此不用添加inline
1/3:初始化,40个*
2/1:
21行:初始化vector,5个42
22行用v1初始化v2
24用at接口访问v1中的第0个元素并赋值为-999
2/2:
32:定义一个二位动态矩阵,第一行初始化为123,第二行初始化为4567
33:用v1初始化v2
35:v1.at()指向第一行的一维容器
.push-back是在这个一维容器后面添加-999
2/3
39:用指向的第一行的动态数组初始化t1
40:输出最后一个元素
42:同39
43:同40
2/4
1.浅复制,因为不会改变原来的值
2.是的
3/1:浅复制
3/2:不能,在主函数运行时,对于line21中x1.at(i)=i*i,左操作数必须为左值
有,test2中权限越界
3/3不可以,返回的是指针常量,相当于对其初始化
四:
代码:
`Matrix::Matrix(int n, int m) :lines{ n }, cols{ m } { ptr = new double[lines * cols]; }
Matrix::Matrix(int n) :lines{ n }, cols{ n } { ptr = new double[lines * cols]; }
Matrix::Matrix(const Matrix& x) :lines{ x.lines }, cols{ x.cols } {
ptr = new double[lines * cols];
for (int i = 0; i < lines; i++)
for (int j = 0; j < cols; j++)
{
ptr[i * cols + j] = x.ptr[i * cols + j];
}
}
Matrix::~Matrix() { delete[]ptr; }
int Matrix::get_lines()const{
return lines;
}
int Matrix::get_cols()const {
return cols;
}
void Matrix::set(const double* pvalue) {
for(int i=0;i<lines;i++)
for (int j = 0; j < cols; j++)
{
ptr[icols+j]= pvalue[icols+j];
}
}
void Matrix::clear() {
for (int i = 0; i < lines; i++)
for (int j = 0; j < cols; j++)
{
ptr[i*cols+j] = 0.0;
}
}
void Matrix::display()const {
for (int i = 0; i < lines; i++){
for (int j = 0; j < cols; j++) {
cout << ptr[i * cols + j] << ", ";
}
cout << "\b\b \n";
}
}
const double& Matrix::at(int i, int j) const{
assert(i >= 0 && i < lines);
assert(j >= 0 && j < cols);
return ptr[i*cols+j];
}
double& Matrix::at(int i, int j) {
assert(i >= 0 && i < lines);
assert(j >= 0 && j < cols);
return ptr[i * cols + j];
}
`
运行结果:
五:
代码`#pragma once
include
include
include
include
using namespace std;
class User {
public:
User(string NAME, string PASSWORD = "123456", string EMAIL = "") :name{ NAME }, password{ PASSWORD }, email{ EMAIL } {}
void set_email() {
string x;
int flag = -1;
cout << "Enter email address:";
cin >> x;
flag = x.find('@');
while (flag == -1) {
cout << "illegal email.Please re-enter email:";
cin >> x;
flag = x.find('@');
}
email = x;
cout << "email is set successfully..." << endl;
}
int change_password() {
int count = 1;
string x;
cout << "Enter old password:";
cin >> x;
while (x != password&&count<3) {
cout << "password input error.Please re-enter again:";
cin >> x;
count++;
}
if (count >= 3) { cout << "password input error.Please try after a while."; return 0; }
if(count<3){
cout << "enter new password:";
cin >> x;
password = x;
cout << "new password is set successfully..." << endl;
return 0;
}
}
void display() {
string x(password.length(),'*');
cout << "name:"<<name << endl;
cout << "pass:" << x << endl;
cout << "email:" << email << endl;
}
private:
string name;
string password;
string email;
};`
运行结果