6-17
指针应该先有地址才可以被赋值,所以改为如下:
#include<iostream> using namespace std; int main() { int i,*p=&i; i=9; cout<<"The value at p:"<<*p; return 0; }6-18
在分配内存使用完后要释放,
#include<iostream> using namespace std; int fn1(); int main() { int a=fn1(); cout<<"the value of a is:"<<a; } int fn1(){ int *p=new int (5); return *p; delete p; }期中:
#include<iostream> #include<cstdlib> using namespace std; class Dice{ public: Dice(int n); int cast(); private: int sides; }; Dice::Dice(int n):sides(n){ } int Dice::cast(){ return rand()%sides+1; } int main() { int amount,number; cout<<"输入班级的人数与学号:"; cin>>amount>>number; Dice A(amount); int i,j; double k; for(i=1;i<=500;i++){ if(A.cast()==amount) j++; } k=(double)j/500; cout<<"选到"<<number<<"学号的概率是:"<<k<<endl; return 0; }
3
book。cpp
#include "book.h" #include <iostream> #include <string> using namespace std; // 构造函数 Book::Book(string isbnX,string titleX,float priceX):isbn(isbnX),title(titleX),price(priceX){ } // 打印图书信息 void Book::print(){ cout<<"出版编号:"<<isbn<<endl; cout<<"书名:"<<title<<endl; cout<<"定价:"<<price<<endl; }book.h
#ifndef BOOK_H #define BOOK_H #include <string> using std::string; class Book { public: Book(string isbnX, string titleX, float priceX); //构造函数 void print(); // 打印图书信息 private: string isbn; string title; float price; }; #endifmain.cpp
#include "book.h" #include <vector> #include <iostream> using namespace std; int main() { // 定义一个vector<Book>类对象 vector<Book> books; string isbn, title; float price; do{ cout<<"输入图书的出版编号,书名,定价:(输出请输入价格为0)"; cin>>isbn>>title>>price; Book x(isbn,title,price); books.push_back(x); }while(price!=0); // 录入图书信息,构造图书对象,并添加到前面定义的vector<Book>类对象中 // 循环录入,直到按下Ctrl+Z时为止 (也可以自行定义录入结束方式) // 输出入库所有图书信息 int i; for(i=0;i<books.size()-1;i++){ books[i].print(); } return 0; }转载于:https://www.cnblogs.com/a18851962010/p/9078725.html