mooophy / cpp-primer Goto Github PK
View Code? Open in Web Editor NEWC++ Primer 5 answers
License: Creative Commons Zero v1.0 Universal
C++ Primer 5 answers
License: Creative Commons Zero v1.0 Universal
According to page 285, in a class if a member uses a name from an outer scope and that name is type, then the class may not subsequently redefine that name. Some compliers accept this error and I compile the example code in page 285 with clang++ result in no error. In Exercise 7.35, in the class the type name Type has been redefined. Shall we still consider redefine the outer type name in class as an error though the compiler accept it?
Assuming txt_size
is a function that takes no arguments and returns anint
value, which of the following definitions are illegal? Explain why.
unsigned buf_size = 1024;
int ia[buf_size]; // legal
int ia[4 * 7 - 14]; // legal
int ia[txt_size()]; // legal
char st[11] = "fundamental"; // illegal, the string's size is 12.
I think
int ia[buf_size]; // illegal
int ia[txt_size()]; // illegal
Obviously,The dimension value must be a constant expression ,But thebuf_size
and txt_size()
is not ,So.....
@pezy
I can't compile this file , the reported is "isnumber function can't be found !"
对于编译的选项,我觉得作者写的不是很明了,可不可以麻烦作者写一个makefile来自动化编译,就像GCC的源码一样。这样作者可以详尽的说明需要GCC的编译选项!
ch09/ex9_32.cpp
FYI, I believe in Update ex9_32.cpp
iter = vi.insert(iter, *iter++); statement
will insert *iter into the container after incrementing the pointer, not before the pre-incremented iter pointer.
tested it with the statement iter = vi.insert(iter, - *iter++); so I could discriminate. The corrected statement should be instead iter = vi.insert(iter, *iter); ++iter;
this statement may also refers to the section of the book 4.1.3 Order of Evaluation, Precedence, and Associativity where incrementing the second argiment will affect the first argument in the insert function
thanks,
dom68
process程序块结束后,p指向的内存会被释放。虽然题中未写delete p;
,但是实际上用户手动调用delete p;
的潜在危险是存在的
Exercise 2.29
(e) p2 = p1;
I think it's illegal, because p2 is a const pointer, so we can't assign a value to it.
ex7_32.h为啥写到一个文件中?写到两个文件中不是更合理吗?我写到两个文件中但是一直出错!!
ch01
├── ex1_10.cpp
├── ex1_11.cpp
├── ex1_16.cpp
├── ex1_1.cpp
├── ex1_20.cpp
├── ex1_21.cpp
├── ex1_22.cpp
├── ex1_23.cpp
├── ex1_9.cpp
├── makefile
└── README.md
ch17
├── ex17.10
│ └── main.cpp
├── ex17.11.12.13
│ └── main.cpp
├── ex17.1.2
│ └── main.cpp
├── ex17.14.15.16
│ └── main.cpp
├── ex17.17.18
│ └── main.cpp
├── ex17.19.20
│ └── main.cpp
├── ex17.21
│ ├── data
│ │ └── record.txt
│ └── main.cpp
├── ex17.28.29.30
│ └── main.cpp
├── ex17.3
│ ├── main.cpp
│ ├── textquery.cpp
│ └── textquery.h
├── ex17.4.5.6.7.8
│ ├── main.cpp
│ ├── Sales_data.cpp
│ └── Sales_data.h
├── ex17.9
│ └── main.cpp
└── makefile
能不能将cpp文件直接放到chXX目录下面,不要再创建新的子目录?
这样建立makefile,自动化编译不好布置。
我已经仿照GCC源码将前11章的自动化编译已经做好了,但是后面几章节的目录结构有点不好搞,而且后面几章节的命令规则和前面也很不相同!
r1 = v2, this is illegal, r1 is normal int & , can not bind to cont int
The exercise description of 15.2 says that:
Define a class that implements a limited discount strategy, which applies a discount to books purchased up to a given limit. If the number of copies exceeds that limit, the normal price applies to those purchased beyongd the limit.
double limit_quote::net_price(std::size_t n)
returns n * price * (n < quantity ? 1 - discount : 1 )
, which should be:
double net_price(size_t n) const override {
if(n <= quantity) return n * price * (1 - discount);
else return quantity * price * (1 - discount)
+ (n - quantity) * price;
}
int main()
{
{
auto sp = std::make_shared(42);
auto p = sp.get();
std::cout<<*(sp.get())<<std::endl;
delete p;
std::cout<<sp.use_count()<<std::endl;
std::cout<<*sp<<std::endl;
}
return 0;
}
Exercise 3.17: Read a sequence of words from cin and store the values a vector. After you’ve read all the words, process the vector and change each word to uppercase. Print the transformed elements, eight words to a line.
see the code
Is there any mix-up between Qs&As ?
(c)也不对
Declarations of Derived Classes
A derived class is declared like any other class (§7.3.3, p. 278). The declaration
contains the class name but does not include its derivation list:
class Bulk_quote : public Quote; // error: derivation list can't appear here
class Bulk_quote; // ok: right way to declare a derived class
r2 is low-level const,底层const或者顶层const是针对指针来说的吧,r2是一个引用,so"r2 is low-level const"对吗?
https://github.com/Mooophy/Cpp-Primer/tree/master/ch03#exercise-320--part1--part2
Links part1 and part2 point to the same content.
Best regards.
The object should be declared const for the member functions "front" and "back".
prev = vi.before_begin();
prev在循环里没有定义, 为什么程序能运行成功, 我觉得迭代器失效了啊.
“used recursion to print the contents of a vector to conditionally print information about its execution. For example, you might print the size of the vector on each call”
In my opinion, there are two requests in this sentence:
The old solution may not match the second.
应该是mathLib::MatrixLib::matrix mathLib::MatrixLib::operator* (const matrix&, const matrix&);
吧?
As with class members defined outside a class, once the fully qualified name is seen, we are in the scope of the namespace.
按中文版的说法,这里应该是“声明并定义了”变量iy。所以答案应该是definition And declaration?
ic = *p3
我觉得是对的啊,因为p3
也指向的是const int
。
Hi, I'm here again :D
Exercise 10.5: In the call to equal on rosters, what would happen if both rosters held C-style strings, rather than library strings?
And the answer given is:
Answer It's the same as
std::string
But I think it is actually not the same as std::string
.
Code given:
int main() {
std::vector<const char *> roster1{"Mooophy", "pezy", "Queequeg"};
std::list<const char *> roster2{"Mooophy", "pezy", "Queequeg", "shbling", "evan617"};
std::cout << std::equal(roster1.cbegin(), roster1.cend(), roster2.cbegin());
}
As we know, c-style strings cannot be compared using ==
and <
and >
, 'casue these relational operators compare addresses in pointers rather than strings represented by char pointers.
And the "Mooophy", "pezy", "Queequeg"
in roster1
and "Mooophy", "pezy", "Queequeg"
in roster2
are all literals, and compiler optimized them to be stored in the same addresses. Thus yielded 1
.
std::cout << (void*)roster1[0] << std::endl;
std::cout << (void*)roster2.front() << std::endl;
On my pc, I got 0x401ec6
and 0x401ec6
.
Then look at this:
int main() {
const char a[3][2] = {"A", "B", "C"};
const char b[3][2] = {"A", "B", "C"};
std::vector<const char*> v1(std::begin(a), std::end(a));
std::list<const char*> v2(std::begin(b), std::end(b));
std::cout << std::boolalpha
<< std::equal(v1.cbegin(), v1.cend(), v2.cbegin()) << std::endl;
return 0;
}
Which yields false
.
So the answer of this exercise depends. But I think the first situation is just a coincidence and should be avoided;
NOTE: If we define a
and b
as pointer array, then the result is true
again.
const char *a[3] = {"A", "B", "C"};
const char *b[3] = {"A", "B", "C"};
So literals of same contents pointed to by pointers share the same memories, but literals in arrays are stored individually.
Contributor @mudongliang:
Your contribution so far is much appreciated. Double check, however, is still a good practice before proposing any pull request. Check whether the PR is really helpful to most C++ beginners, making sure it is not wasting maintainers' time.
I don't like blocking any user, so please value the time we are still studying and working together.
Mooophy.
April 09, 2015 Auckland
ex3_21_generics_version.cpp uses C++ advanced feature - Template!
Chapter 3 focus on the String ,Vector,Array! Template is the topic of Chapter 16.
This version of ex3_21 will confuse newbie including me !
So I suggest @Mooophy to delete it in the future version!
Or move ex3_21_generics_version.cpp to ch16 as an improved solution which applies template to an exercise!
The action is same to ex3_16. The current version has lost in code reuse!
We can put the function version in ch06 as an improved version, and put the generics version in ch16 as an more improved version ! I think this is good for newbie to apply advanced feature in the same environment!
@Mooophy , I think we should add some simple make usage in README.md in the root directory to help the newer to know how to automake compile our project !
How you think it ??
@pezy , First , Thank you for accepting and trying to write makefile !
But you should test makefile by executing "make all" in the ch**,or the root directory !
Makefile of the root directory is to execute makefile in the ch**.
This is my fault ! I only want you to use makefile ,But I don't give the readme for it !
Maybe I should write a simple todo to tell how to make and how to write a makefile !
题目并没有要求函数的参数类型吧?
我以为string (&func(/* any possible parameters */))[10]
就行了。
I try to change the file constructor of chapter 17 , but when I see the directory of ex17.3 , I find that the source code is not complete ! It lacks a header file !
Now I will let it alone ! And I will comment it in the makefile !
even though if(p)
returns true
, we cannot confirm that p
points to a valid object.
eg. if p
points a location one past the end of some object. if(p)
also returns true
.
So I think we can't determine whether a point points a valid object.
https://github.com/Mooophy/Cpp-Primer/tree/master/ch02#exercise-238
You wrote: "...
// different
auto c = r;
decltype(r) d = i;"
It's true that "c" (int type) and "d" (int& type) are different, what I pointed out is the assignement to "d" from "i". Why? Shouldn't it be from "r" as previous "c" assignement? Therefore the above code it should be:"...
// different "c" will be int "d" will be int&
auto c = r;
decltype(r) d = r;"
Best regards
I'm not sure whether I should merge pull request #175 or not. makefile
is useful, but it seems a little far away from the content of CP5. So what's your opinion?
Please reply this issue with:
Yes, merge it.
Or:
No, please don't merge it
I'll count votes in 5 days.Thx for help.
class Clock{
public:
Clock(int newH = 0, int newM = 0, int newS = 0);
Clock(Clock &clock);
Clock(Clock &&clock);
void setTime(int newH = 0, int newM = 0, int newS = 0);
void showTime();
int getHour();
int getMinute();
int getSecond();
private:
int hour, minute, second;
};
Clock::Clock(int newH, int newM, int newS){
hour = newH;
minute = newM;
second = newS;
cout<<"call init function!"<<endl;
}
Clock::Clock(Clock &clock){
hour = clock.hour;
minute = clock.minute;
second = clock.second;
cout<<"call dumplicate init function!"<<endl;
}
bool isAm(Clock c){ //require 24 hour
return (c.getHour() < 12);
}
Clock create(){
Clock c(1,2,3);
return c;
}
-----------------why create function is wrong when I try to call it ??????
@pezy , @Mooophy
https://github.com/Mooophy/Cpp-Primer/blob/master/ch03/README.md#exercise-329
You wrote:
3. no arrays of references.
Neither vector allows to be instantiated with references therefore there aren't vector of references. I suggest:
3. size must be known at compile time.
HTH
Best regards.
k
,k2
应该是const &int
, 而j2
为const int
。
验证代码:http://ideone.com/5h8SUs
这一题的代码中用到了9.32中已经证明是illegal的语句iter = vi.insert(iter, *iter++);
,似乎不太妥当。
In Ch13 , the Header File need to be arranged !
In ex13.1.2.3.cpp , the header file "StrBlob.h" dosen't exist !
And there are the header with same name , but with a little difference !
For example , StrBlob.h , Alan.h
Is there any chance to merge them ? If it can , put the header file in the root dir of ch13.
https://github.com/Mooophy/Cpp-Primer/tree/master/ch02#exercise-230
You wrote: "v2 is top-level const, p2 is low-level const. p3: right-most const is top-level, left-most is low-level. r2 is low-level const."
It should be: "v2 is top-level const, p2 is low-level const. p3 is both top-level const and low-level const. r2 is low-level const."
IMHO
Best regards.
除了iter
的值没有改变以外,是否还有迭代器失效的问题?毕竟发生了insert操作。
表9.5中说,向一个vector、string或者deque中插入元素会使得所有指向容器的迭代器、引用和指针失效。
Although conditional operator is concise , but I think the three layers of nested conditional operator is less intelligible than if...else...statements!
To accomplish the test we intended, we can rewrite the expression as follows: i != j && j < k
What's the meaning of this sentence?
i != j < k is same as i != (j < k)
but it no equals to i != j && j < k
For example , i = 0 , j = 0 , k = 1
i != j && j < k = 0
i != (j<k) = 1
when I compile with: using GCC 4.9.2 with option -std=c++11
pv = const_cast<string*>(ps);
I get this error:
ex4_37.cpp: In function 'int main()':
ex4_37.cpp:27:33: error: static_cast from type 'const string* {aka const std::basic_string}' to type 'std::string {aka std::basic_string}' casts away qualifiers pv = static_cast<string>(ps);
pv = static_cast<void*>(const_cast<string*>(ps));
works
(c) Since i * ci is an rvalue, so T is int, val is int&&
https://github.com/Mooophy/Cpp-Primer/tree/master/ch03#exercise-39
You wrote:
invalid in theory, but the compiler passes.
s is empty, so s[0] is undefined. But the compiler always define s[0] with \0, so you can use s[0] in the cout.
This is really wrong, you can use [0] [10] [1000] with the substring operator but the behaviour is not predictable, the compiler doesn't store a null char in [0] neither [1000] etc.
What the compiler passes it is using an undefined object accessed by the subscript operator to out of range value that it must be avoided from the programmer not the compiler, for further information please take a look here: http://en.wikipedia.org/wiki/Undefined_behavior
Best regards.
能不能详细的解释一下练习13.57呢?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.